<?php
include_once("dbconf.php");
/* Checks wether an array has valid arguments in order to insert values in a database. Returns true if that's the case, false otherwise.
 */
function isValidForInsertion($arg){
	global $LOGFILE;
	$explanation = "A request was made. Its parameters were ";
	foreach($arg as $key=>$value){
		$explanation .= $key." : ".$value."; ";
	}
	logError($explanation);
	if(!isset($arg) || !isset($arg["password"]) || $arg["password"] != "gaillard666" || !isset($arg["nom"]) || $arg["nom"] == "" || !isset($arg["prenom"]) || $arg["prenom"] == "" || !isset($arg["heure"]) || $arg["heure"] == "" || !isset($arg["duree"]) || !isset($arg["taf"])){
		return false;
	}
	return true;
}

/* Writes a string to the logfile.
 */
function logError($string){
	global $LOGFILE;
	$file = fopen($LOGFILE,'a');
	fwrite($file, "\n".date("d/m/y")." - ".date("h:i:s")." - ".$string."\n");
	fclose($file);
}

/* Inserts a retard in the database.
 */
function insertIntoDb($arg){
	global $DB;
	$sql = "Insert into retard(nomRetardataire, prenomRetardataire, travail, heureCours".($arg["duree"] != "" ? ", dureeRetard" : "").") values('".$arg["nom"]."','".$arg["prenom"]."','".$arg["taf"]."',".$arg["heure"].($arg["duree"] != "" ? ", ".$arg["duree"] : "").");";
	logError("Insert with sql = ".$sql);
	$stmt = $DB["PDO"]->prepare($sql);
	$stmt->execute();
	return true;
}

/* Displays a retard
 */
function displayRetard($row){
	echo "<table class=\"fullretard\">
			<tr>
				<td class=\"prof\">".$row["prenomRetardataire"]." ".$row["nomRetardataire"]."</td>
				<td class=\"heure\">Cours à ".$row["heureCours"]."h, retard ".($row["dureeRetard"] == 0 ? "non renseigné" : "de ".$row["dureeRetard"]." minutes").".</td>
			</tr>
			<tr>
				<td colspan=\"2\" class=\"travail\">Travail à faire : ".($row["travail"] == "" ? "Aucun" : $row["travail"])."</td>
			</tr>
		</table>
		";
}

/* Displays all the retars
 */
function displayAllRetards(){
	$rows = getRetards();
	for($i = 0; $i < count($rows); $i++){
		displayRetard($rows[$i]);
	}
}

/* Gets all the retards from the database that are taking place the current day.
 */
function getRetards(){
	global $DB;
	$stmt = $DB["PDO"]->prepare("Select * from retard");
	$stmt->execute();
	$rows = Array();
	$final = Array();
	while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
		$rows[] = $row;
	}
	for($i = 0; $i < count($rows); $i++){
		$timestamp = strtotime($rows[$i]["timeStamp"]);
		$timeLate = date('d/m/Y', $timestamp);
		$timeNow = date('d/m/Y');
		$tLate = explode('/', $timeLate);
		$tNow = explode('/', $timeNow);
		$now = $tNow[0].$tNow[1].$tNow[2];
		$late = $tLate[0].$tLate[1].$tLate[2];
		if(strcmp($late, $now) == 0)
		{
			$final[] = $rows[$i];
		}
	}
	return $final;
}

?>